﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;

namespace MQ
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }
        NLog.ILogger log = NLog.LogManager.GetLogger("f");
         MqttFactory factory = new MqttFactory();
          IMqttClient client;
         private mqMsg msg;
        dispMsg dmsg;
        private int id=0;
     
        private async  void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            //this.Dispatcher.Invoke(new Action(delegate {  }));
           await clientConnectAsync();
        
        }

        private async void btnSubscribe_Click(object sender, RoutedEventArgs e)
        {
           await SubTopicAsync("/top1");
         
        }

        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
           await PubMsgAsync("hello world");
        }

       async Task clientConnectAsync()
        {
            client = factory.CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                .WithClientId("Client1")
                .WithTcpServer("193.112.127.87", 1883)
                .WithCredentials("admin", "admin")
                //.WithTls()
                .WithCleanSession()
                .Build();
            await client.ConnectAsync(options);
            log.Info("连接状态：" + client.IsConnected.ToString());

            client.UseApplicationMessageReceivedHandler(e => {
                log.Info("收到信息："+e.ApplicationMessage.Payload);

            });
        }

        async Task PubMsgAsync(string msg)
        {
            var message = new MqttApplicationMessageBuilder()
             .WithTopic("/top1")
             .WithPayload(msg)
             .WithExactlyOnceQoS()
             .WithRetainFlag()
             .Build();
            await client.PublishAsync(message);
            log.Info("发布信息：/" +msg);
        }

        async Task SubTopicAsync(string topic)
        {
            await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("/" + topic).Build());
            log.Info("订阅主题：/" + topic);
        }

        //private void Client_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        //{
        //    msg = new mqMsg();
     
        //    msg.Topic = e.ApplicationMessage.Topic;
        //    msg.Payload = Encoding.Default.GetString(e.ApplicationMessage.Payload);
        //    msg.QoS = e.ApplicationMessage.QualityOfServiceLevel.ToString();
        //    msg.Retain = e.ApplicationMessage.Retain.ToString();
        //    dmsg = new dispMsg();
        //    this.Dispatcher.Invoke(new Action(() =>
        //    {
        //        id++;
        //        dmsg.id = id;
        //        dmsg.msgContent = msg.Payload;
        //        lstMsg.Items.Insert(0, dmsg);
        //    }));
        //}

    }
}
